package com.next

import grails.transaction.Transactional
import org.springframework.security.access.annotation.Secured

import static org.springframework.http.HttpStatus.*

@Secured(['ROLE_ADMINISTRATOR', 'ROLE_COMPANY_ADMINISTRATOR', 'ROLE_COMPANY_USER'])
@Transactional(readOnly = true)
class LeadController
{

    static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]

    def springSecurityService
    def exportService

    def index(Integer max)
    {
        def username = springSecurityService?.getPrincipal()?.username
        def leadList = Lead.findAll("from Lead where user.username = '${username}' and active = true order by createdDate desc", [max: params.max ?: 10, offset: params.offset ?: 0])
        def count = Lead.executeQuery("select count(id) from Lead where user.username = '${username}' and active = true")

        respond leadList, model: [leadCount: count[0]]
    }

    def show(Lead lead)
    {
        Company company = Company.findAll()[0]
        Boolean enableTerritory = company.enableAccountTerritory

        def addressList = Address.findAll("from Address where lead.id = ?", [lead.id])
        def teamList = LeadTeam.findAll("from LeadTeam where lead.id = ?", [lead.id])
        def flexFieldInstanceList = FlexFieldInstance.findAll("from FlexFieldInstance where lead.id = ?", [lead.id])
        respond lead, model: [addressList: addressList, teamList: teamList, flexFieldInstanceList: flexFieldInstanceList, enableTerritory: enableTerritory]
    }

    def create()
    {
        respond new Lead(params)
    }

    @Transactional
    def save(Lead lead)
    {
        if (lead == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (lead.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond lead.errors, view: 'create'
            return
        }

        lead.save flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.created.message', args: [message(code: 'lead.label', default: 'Lead'), lead.id])
                redirect lead
            }
            '*' { respond lead, [status: CREATED] }
        }
    }

    def edit(Lead lead)
    {
        respond lead
    }

    @Transactional
    def update(Lead lead)
    {
        if (lead == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (lead.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond lead.errors, view: 'edit'
            return
        }

        lead.save flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.updated.message', args: [message(code: 'lead.label', default: 'Lead'), lead.id])
                redirect lead
            }
            '*' { respond lead, [status: OK] }
        }
    }

    @Transactional
    def delete(Lead lead)
    {

        if (lead == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        lead.delete flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.deleted.message', args: [message(code: 'lead.label', default: 'Lead'), Lead.id])
                redirect action: "index", method: "GET"
            }
            '*' { render status: NO_CONTENT }
        }
    }

    protected void notFound()
    {
        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.not.found.message', args: [message(code: 'lead.label', default: 'Lead'), params.id])
                redirect action: "index", method: "GET"
            }
            '*' { render status: NOT_FOUND }
        }
    }

    @Transactional
    def searchLead()
    {
        def username = springSecurityService?.getPrincipal()?.username
        def fullName = params["fullName"]
        def cellphone = params["cellphone"]
        def company = params["company"]

        String sql = "from Lead as u where 1=1 and u.user.username = '${username}' and u.active = true"
        if (fullName)
        {
            sql += " and u.fullName like '%${fullName}%'"
        }
        if (cellphone)
        {
            sql += " and u.cellphone like '%${cellphone}%'"
        }
        if (company)
        {
            sql += " and u.company.id = ${company}"
        }
        String countSql = "select count(u.id) " + sql
        sql += ' order by createdDate desc'

        def list = Lead.findAll(sql, [max: params.max ?: 10, offset: params.offset ?: 0])
        def count = Lead.executeQuery(countSql)

        def lead = new Lead(params)
        respond list, model: [leadCount: count[0], lead: Lead, params: params], view: 'index'
    }

    @Transactional
    def exportLead()
    {
        def username = springSecurityService?.getPrincipal()?.username
        def fullName = params["fullName"]
        def cellphone = params["cellphone"]
        def company = params["company"]

        String sql = "from Lead as u where 1=1 and u.user.username = '${username}' and u.active = true"
        if (fullName)
        {
            sql += " and u.fullName like '%${fullName}%'"
        }
        if (cellphone)
        {
            sql += " and u.cellphone like '%${cellphone}%'"
        }
        if (company)
        {
            sql += " and u.company.id = ${company}"
        }
        String countSql = "select count(u.id) " + sql
        sql += ' order by createdDate desc'

        def list = Lead.findAll(sql)
        def count = Lead.executeQuery(countSql)
        if (params?.f && params.f != "html")
        {
            response.contentType = grailsApplication.config.grails.mime.types[params.f]
            response.setHeader("Content-disposition", "attachment; filename=lead.${params.extension}")
            List fields = ["company", "numberOfEmployees", "industry.name", "website", "address", "rating.name", "status.name", "fullName", "salutation", "title", "email", "cellphone", "phone", "description", "createdDate", "modifiedDate"]
            Map labels = ["company": "公司名称", "numberOfEmployees": "人数", "industry.name": "行业", "website": "网站", "address": "地址", "rating.name": "评级", "status.name": "状态", "fullName": "姓名", "salutation": "称谓", "title": "头衔", "email": "邮件", "cellphone": "手机", "phone": "座机", "description": "线索描述", "createdDate": "创建时间", "modifiedDate": "修改时间"]
            exportService.export(params.f, response.outputStream, list, fields, labels, [:], [:])
        }
    }

    def changeToOpportunity(Lead lead)
    {
        Company company = Company.findAll()[0]
        Boolean enableTerritory = company.enableAccountTerritory

        def username = springSecurityService.getPrincipal().username
        def user = User.findByUsername(username)

        respond lead, model: [enableTerritory: enableTerritory, user: user]
    }

    @Transactional
    def changeToOpportunitySave(Lead lead)
    {

        println params

        def username = springSecurityService.getPrincipal().username
        def user = User.findByUsername(username)

        def enableTerritory = params['enableTerritory']
        def territoryName = params["territoryName"]
        if (enableTerritory == "true" && !territoryName)
        {
            flash.message = "请选择销售区域"
            respond lead, model: [enableTerritory: enableTerritory, user: user], view: 'changeToOpportunity'
            return
        }

        def accountName = params["accountName"]
        if (!accountName)
        {
            flash.message = "请输入客户姓名"
            respond lead, model: [enableTerritory: enableTerritory, user: user], view: 'changeToOpportunity'
            return
        }

        def contactName = params["contactName"]
        if (!contactName)
        {
            flash.message = "请输入联系人姓名"
            respond lead, model: [enableTerritory: enableTerritory, user: user], view: 'changeToOpportunity'
            return
        }

        def accountType = params["accountType"]
        if (!accountType)
        {
            flash.message = "请输入客户类型"
            respond lead, model: [enableTerritory: enableTerritory, user: user], view: 'changeToOpportunity'
            return
        }

        def website = params["website"]
        def parent = params["parent"]
        def industry = params["industryName"]
        def numberOfEmployees = params["numberOfEmployees"]
        def salutation = params["salutationName"]
        def cellphone = params["cellphone"]
        def phone = params["phone"]
        def title = params["title"]
        def email = params["email"]

        Account account = Account.findByName(accountName)
        if (!account)
        {
            account = new Account()
            account.name = accountName
        }

        if (Territory.findByName(territoryName))
        {
            account.territory = Territory.findByName(territoryName)
        }

        account.type = AccountType.findByName(accountType)
        account.parent = Account.findById(parent)
        account.website = website
        account.industry = Industry.findByName(industry)
        account.numberOfEmployees = numberOfEmployees?.toInteger()

        if (account.validate())
        {
            account.save flush: true
        }
        else
        {
            println account.errors
            flash.message = "转换商机失败，请检查客户信息是否完善"
            respond lead, model: [enableTerritory: enableTerritory, user: user], view: 'changeToOpportunity'
            return
        }

        Contact contact = new Contact()
        contact.account = account
        contact.type = ContactType.findByName("日常联系人")
        contact.fullName = contactName
        contact.salutation = Salutation.findByName(salutation)
        contact.cellphone = cellphone
        contact.phone = phone
        contact.title = title
        contact.email = email

        if (contact.validate())
        {
            contact.save flush: true
        }
        else
        {
            println contact.errors
            flash.message = "转换商机失败，请检查客户信息是否完善"
            respond lead, model: [enableTerritory: enableTerritory, user: user], view: 'changeToOpportunity'
            return
        }

        Opportunity opportunity = new Opportunity()
        opportunity.account = account
        opportunity.status = OpportunityStatus.findByName("跟进中")
        if (opportunity.validate())
        {
            opportunity.save flush: true
        }
        else
        {
            println opportunity.errors
            flash.message = "转换商机失败，请检查线索信息是否完善"
            respond lead, model: [enableTerritory: enableTerritory, user: user], view: 'changeToOpportunity'
            return
        }

        lead.active = false

        if (lead.validate())
        {
            lead.save flush: true
        }
        else
        {
            println lead.errors
            flash.message = "转换商机失败，请检查线索信息是否完善"
            respond lead, model: [enableTerritory: enableTerritory, user: user], view: 'changeToOpportunity'
            return
        }

        redirect controller: 'opportunity', action: "index"
    }
}
